package com.story.web.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.story.domain.Admin;
import com.story.domain.User;
import com.story.service.IAdminService;
import com.story.web.shiro.token.StoryLoginToken;

public class AdminRealm extends AuthorizingRealm {
	@Autowired
	private IAdminService adminService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// 认证方法
		StoryLoginToken loginToken = (StoryLoginToken) token;
		String username = loginToken.getUsername();
		Admin admin = adminService.findOneByUsername(username);
		if(admin==null){
			throw new UnknownAccountException("用户不存在!");
		}
		if(Boolean.FALSE.equals(admin.getAccountStatus())){
			throw new LockedAccountException("账号已锁定！");
		}
		Object principal = username;
		Object credentials = admin.getPassword();
		ByteSource credentialsSalt = ByteSource.Util.bytes(admin.getSalt());
		String realmName = getName();
		
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,
				credentials, credentialsSalt, realmName);
		return info;
	}

}
